package cn.stylefeng.guns.core.util;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import java.net.MalformedURLException;

public class MapUtils {

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
    /**
     * 计算两个经纬度之间的距离
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double GetDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s*1000;
        return s;
    }


    public static double haversineDistance(double lat1, double lon1, double lat2, double lon2) {
        // 将角度转换为弧度
        lat1 = Math.toRadians(lat1);
        lon1 = Math.toRadians(lon1);
        lat2 = Math.toRadians(lat2);
        lon2 = Math.toRadians(lon2);

        // Haversine公式计算
        double dlon = lon2 - lon1;
        double dlat = lat2 - lat1;
        double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2), 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distance = EARTH_RADIUS * c;

        return distance; // 返回距离，单位为公里
    }
    
    public static void main(String[] args) throws MalformedURLException {

//        // 连接字符串
//        String connectionString = "mongodb://xf:xf@117.72.107.196:27017";
//
//        // 创建MongoClient实例
//        try (MongoClient mongoClient = MongoClients.create(connectionString)) {
//            // 获取数据库
//            MongoDatabase database = mongoClient.getDatabase("xf_map_db");
//
//            // 获取集合，如果不存在则创建
//            MongoCollection<Document> collection = database.getCollection("users");
//
//            // 创建一个文档
//            Document doc = new Document("name", "John Doe")
//                    .append("age", 30)
//                    .append("city", "New York");
//
//            // 插入文档
//            collection.insertOne(doc);
//            System.out.println("Document inserted successfully");
//        }
    }
}
